package cn.wolfcode.util;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public String handleException(RuntimeException ex, HandlerMethod handlerMethod, HttpServletResponse httpServletResponse) throws IOException {
        // 把异常信息打印出来 方便找BUG
        ex.printStackTrace();

        // 判断执行的方式是不是需要返回 Json 数组
        if (handlerMethod.hasMethodAnnotation(ResponseBody.class)) {
            // 如果贴了注解 表示需要json
            JsonResult json = new JsonResult(false, "操作失败");
            // 使用response对象输出数据(json字符串)
            httpServletResponse.setContentType("application/json;charset=utf-8");
            httpServletResponse.getWriter().print(JSON.toJSONString(json));

            return null;

        }
        // 如果不是 则返回错误视图
        return "common/error";

    }
}
